package com.example.demo.service.impl;

import com.example.demo.mapper.UserMapper;
import com.example.demo.pojo.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper = null;

    @Override
    // spring数据库事务机制
    @Transactional(isolation = Isolation.READ_COMMITTED, timeout = 1)
    @CachePut(value = "redisCache", key = "'redis_user_'+#id")
    public User getUser(Long id) {
        return userMapper.getUser(id);
    }

    /**
     * 插入哟用户后，最后mybatis会回填id，取出id缓存用户
     * @param user 对象表
     * @return 添加的结果
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, timeout = 1)
    @CachePut(value = "redisCache", key = "'redis_user_'+#result.id")
    public User insertUser(User user) {
        userMapper.insertUser(user);
        return user;
    }

    // 更新数据后，更新缓存，如果condition配置项使结果集返回为null，不缓存
    @Override
    @Transactional
    @Cacheable(value = "redisCache", condition = "#result != 'null'", key = "'redis_user_'+#id")
    public User updateUser(Long id, String userName) {
        User user = this.getUser(id);
        if (user == null) return null;
        user.setUserName(userName);
        userMapper.updateUser(user);
        return user;
    }

    // 移除缓存
    @Override
    @Transactional
    @CacheEvict(value = "redisCache", key = "'redis_user_'+#id", beforeInvocation = false)
    public int deleteUser(Long id) {
        return userMapper.deleteUser(id);
    }

    // 命中率低，不采用缓存
    @Override
    @Transactional
    public List<User> findUser(String userName, String note) {
        return userMapper.findUser(userName, note);
    }
}
